package com.example.websocket.service.impl;

import com.example.websocket.service.WebSocketService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;


@ServerEndpoint("/ws")
@Service
public class WebSocketServiceImpl {
    private static int onlintCount=0;
    private static CopyOnWriteArraySet<WebSocketServiceImpl> webSocketSet=new CopyOnWriteArraySet<>();
    private Session session;

    @OnOpen
    public void onOpen(Session session){
        this.session=session;
        webSocketSet.add(this);
        addOnlineCount();
        System.out.println("有新的连接加入！当前在线人数为"+getOnlineCount());
        try {
            sendMessage("有新的连接加入！！");
        }catch (IOException e){
            System.out.println("IO异常");
        }
    }

    @OnClose
    public void onClose(){
        webSocketSet.remove(this);
        subOnlineCount();
        System.out.println("有一个连接关闭！当前在线人数为"+getOnlineCount());
    }

    @OnMessage
    public void onMessage(String message,Session session) throws IOException {
        if (StringUtils.isEmpty(message)){
            message="消息为空";
        }
        System.out.println("来自客户端的消息："+message);
//        群发消息
        for (WebSocketServiceImpl item:webSocketSet){
//            String username=item.getSession().getUserPrincipal().getName();
//            System.out.println(username);
            item.sendMessage("server:"+message);
        }



    }
    @OnError
    public void onError(Session session,Throwable error){
        System.out.println("发生错误");
        error.printStackTrace();
    }

/**
 * 发送消息
 */
    private void sendMessage(String message) throws IOException{
        this.session.getBasicRemote().sendText(message);
    }

    private static synchronized int getOnlineCount(){
        return onlintCount;
    }
    private static synchronized void addOnlineCount(){
        WebSocketServiceImpl.onlintCount++;
    }
    private static synchronized void subOnlineCount(){
        WebSocketServiceImpl.onlintCount--;
    }

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }
}
